package com.lys.blog.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lys.blog.dao.mapper.ArticleMapper;
import com.lys.blog.dao.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class ThreadService {

    @Autowired
    private ArticleMapper articleMapper;

    //期望操作在线程池中执行
    @Async("taskExecutor")
    public void updateArticleViewCount(Article article) {
        //原始阅读量
        Integer viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaUpdateWrapper<Article> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Article::getId, article.getId());
        // 保证多线程环境下安全
        //update article set view_count=100 where view_count=99 and id=1
        wrapper.eq(Article::getViewCounts, viewCounts);
        articleMapper.update(articleUpdate, wrapper);
        try {
            Thread.sleep(5000);
            System.out.println("更新完成!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
